package com.journey.org.ui.mine.collection.detail

import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.journey.org.app.TitleViewModel
import com.journey.org.app.requestBase
import com.journey.org.app.requestHttpManager
import com.journey.org.entity.MineCollectionEntity
import com.journey.org.ui.web.WebActivity
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand

class CollectionDetailViewModel(application: Application) : TitleViewModel(application) {

    override fun onCreate() {
        super.onCreate()
        onToolbarTitle.set("收藏详情")
    }

    // 点击分享
    val onClickShareCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            share(
                onCollectionDetailField.get()?.collectionTitle!!,
                onCollectionDetailField.get()?.collectionAddress!!
            )
        }
    })

    private fun share(title: String, url: String) {
        var intentShare = Intent()
        intentShare.action = Intent.ACTION_SEND
        intentShare.type = "text/plain"
        intentShare.putExtra(Intent.EXTRA_SUBJECT, title)
        intentShare.putExtra(Intent.EXTRA_TEXT, url)
        intentShare = Intent.createChooser(intentShare, title)
        startActivity(intentShare)
    }

    // 点击展示收藏页面
    val onClickEnterWebCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("loadUrl", onCollectionDetailField.get()?.collectionAddress)
            bundle.putString("title", onCollectionDetailField.get()?.collectionTitle)
            startActivity(WebActivity::class.java, bundle)
        }
    })

    // 收藏ID
    val onCollectionIdField = ObservableField<String>()

    // 收藏详情数据
    val onCollectionDetailField = ObservableField<MineCollectionEntity>()

    // 刷新
    val onRefreshCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            loadCollectionDetailById()
        }
    })

    fun loadCollectionDetailById() {
        showLoadDialog()
        val params = HashMap<String, Any>()
        params["id"] = onCollectionIdField.get()!!
        requestBase<MineCollectionEntity> {
            requestHttpManager {
                onLoader {
                    loadCollectionDetailById(params)!!
                }
                onSuccess {
                    if (!TextUtils.isEmpty(it.collectionTitle)) {
                        onToolbarTitle.set(it.collectionTitle)
                    }
                    onCollectionDetailField.set(it)
                }
                onComplete {
                    dismissLoadDialog()
                }
            }

        }
    }

}